package ch.zbw.swt.sysventory.network.scan;

import java.util.ArrayList;
import java.util.List;

import ch.zbw.swt.sysventory.hibernate.entity.Computer;
import ch.zbw.swt.sysventory.hibernate.entity.Volume;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ScanVolume {

	// Initialise Object Data types
	private List<Volume> volumes;
	private Computer computer;

	// Constructor
	public ScanVolume(Computer computer) {
		// Create Listobject
		this.volumes = new ArrayList<Volume>();
		this.computer = computer;
	}

	// Get Software
	public List<Volume> getVolumes(String host) {
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM win32_LogicalDisk";
		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// Das Resultat ist eine Datensammlung
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;

			while (enumVariant.hasMoreElements()) {

				item = enumVariant.nextElement().toDispatch();

				final long MEGABYTE = 1024L * 1024L;

				long freeDiskspaceLong = Long.valueOf(
						(Dispatch.call(item, "FreeSpace")).toString())
						.longValue();
				long totalDiskspaceLong = Long.valueOf(
						(Dispatch.call(item, "Size")).toString()).longValue();

				String diskname = Dispatch.call(item, "DeviceID").toString();

				long freeDiskspace = freeDiskspaceLong / MEGABYTE;
				long totalDiskspace = totalDiskspaceLong / MEGABYTE;

				Volume volume = new Volume(freeDiskspace, totalDiskspace,
						diskname, computer);
				volumes.add(volume);
			}
		} catch (Exception e) {

		}
		return volumes;

	}
}
